/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.grouporder.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.api.utils.KuaidiEntity;
import com.jeeplus.modules.api.utils.KuaidiUtils;
import com.jeeplus.modules.api.utils.ToolsUtil;
import com.jeeplus.modules.product.entity.ProductSkuname;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.utils.net.HttpClientUtil;
import com.jeeplus.modules.delivery.entity.Delivery;
import com.jeeplus.modules.delivery.service.DeliveryService;
import com.jeeplus.modules.grouporder.entity.GroupOrder;
import com.jeeplus.modules.grouporder.service.GroupOrderService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;

import static com.jeeplus.modules.grouporder.service.GroupOrderService.*;

/**
 * 拼团订单Controller
 * @author lixinapp
 * @version 2019-10-26
 */
@Controller
@RequestMapping(value = "${adminPath}/grouporder/groupOrder")
public class GroupOrderController extends BaseController {

	@Autowired
	private GroupOrderService groupOrderService;
	@Autowired
	private DeliveryService deliveryService;
	
	@ModelAttribute
	public GroupOrder get(@RequestParam(required=false) String id) {
		GroupOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = groupOrderService.get(id);
		}
		if (entity == null){
			entity = new GroupOrder();
		}
		return entity;
	}

	/**
	 * 拼团订单列表页面
	 */
	@RequiresPermissions("grouporder:grouporder:list")
	@RequestMapping(value = {"list", ""})
	public String list(GroupOrder groupOrder, Model model) {
		model.addAttribute("groupOrder", groupOrder);
		return "modules/grouporder/groupOrderList";
	}

	/**
	 * 拼团订单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("grouporder:groupOrder:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(GroupOrder groupOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 判断当前登录用户
		User user = UserUtils.getUser();
		if (user.isShop()) {
			groupOrder.setDataScope(" AND store.user_id = '" + user.getId() + "' ");
		}
		Page<GroupOrder> page = groupOrderService.findPage(new Page<GroupOrder>(request, response), groupOrder);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑拼团订单表单页面
	 */
	@RequiresPermissions(value={"grouporder:groupOrder:view","grouporder:groupOrder:add","grouporder:groupOrder:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(GroupOrder groupOrder, Model model) {
		model.addAttribute("groupOrder", groupOrder);
		return "modules/grouporder/groupOrderForm";
	}

	/**
	 * 保存拼团订单
	 */
	@ResponseBody
	@RequiresPermissions(value={"grouporder:groupOrder:add","grouporder:groupOrder:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(GroupOrder groupOrder, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(groupOrder);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		groupOrderService.save(groupOrder);//保存
		j.setSuccess(true);
		j.setMsg("保存拼团订单成功");
		return j;
	}
	
	/**
	 * 发货页面
	 */
	@RequestMapping(value = "sendForm")
	public String sendForm(GroupOrder groupOrder, Model model) {
		// 查询物流
		Delivery delivery = new Delivery();
		delivery.setState("0");
		List<Delivery> list = deliveryService.findList(delivery);
		model.addAttribute("groupOrder", groupOrder);
		model.addAttribute("deliveryList", list);
		return "modules/grouporder/sendForm";
	}
	
	/**
	 * 物流动态
	 */
	@RequestMapping(value = "deliveryInfo")
	public String deliveryInfo(GroupOrder groupOrder, Model model) {
		try {
			if (StringUtils.isNotBlank(groupOrder.getExpressCode()) && StringUtils.isNotBlank(groupOrder.getExpressNo())) {
//				String result = HttpClientUtil.doGet("http://www.whyd365.com/customapi/api.php?type=getExpressList&express="+groupOrder.getExpressCode()+"&expresssn=" + groupOrder.getExpressNo());
				new KuaidiEntity(groupOrder.getExpressNo(),groupOrder.getExpressCode());
				String result = ToolsUtil.send();
				logger.debug("物流接口数据：\n" + result);
				if (StringUtils.isNotBlank(result)) {
					JSONObject object = JSONObject.parseObject(result);
					if ("0000".equals(object.getString("code"))) {
						JSONArray array = object.getJSONArray("data");
						//Collections.reverse(array);
						model.addAttribute("result", array);
					}
				}
			}
			
		} catch (Exception e) {
			logger.error("物流动态查询失败！" + e.getMessage());
		}
		return "modules/grouporder/deliveryInfo";
	}
	/**
	 * 发货
	 */
	@ResponseBody
	@RequestMapping(value = "send")
	public AjaxJson send(String id, String deliveryId, String emsNo) throws Exception{
		AjaxJson j = new AjaxJson();
		j.setSuccess(false);
		j.setMsg("操作失败，请刷新后重试");
		
		if (StringUtils.isBlank(deliveryId) || StringUtils.isBlank(emsNo)) {
			j.setMsg("数据不完整");
			return j;
		}
		GroupOrder order = groupOrderService.get(id);
		if (order != null && "1".equals(order.getState())) {
			Delivery delivery = deliveryService.get(deliveryId);
			if (delivery != null) {
				order.setState("2");
				order.setSendDate(new Date());
				order.setExpressCode(delivery.getCode());
				order.setExpressName(delivery.getCorp());
				order.setExpressNo(emsNo);
				//生成指定长度的随机字符串
//				String str= RandomStringUtils.randomAlphanumeric(5);
//				order.setThCode(str);
				order.setExpireDate(DateUtils.addDays(new Date(), 15));
				groupOrderService.send(order);
				
				j.setSuccess(true);
				j.setMsg("操作成功");
			}
		}
		return j;
	}
	
	/**
	 * 删除拼团订单
	 */
	@ResponseBody
	@RequiresPermissions("grouporder:groupOrder:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(GroupOrder groupOrder) {
		AjaxJson j = new AjaxJson();
		groupOrderService.delete(groupOrder);
		j.setMsg("删除拼团订单成功");
		return j;
	}
	
	/**
	 * 批量删除拼团订单
	 */
	@ResponseBody
	@RequiresPermissions("grouporder:groupOrder:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			groupOrderService.delete(groupOrderService.get(id));
		}
		j.setMsg("删除拼团订单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("grouporder:groupOrder:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(GroupOrder groupOrder, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			User user = UserUtils.getUser();
			if (user.isShop()) {
				groupOrder.setDataScope(" AND store.user_id = '"+user.getId()+"' ");
			}
            String fileName = "拼团订单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<GroupOrder> page = groupOrderService.findPage(new Page<GroupOrder>(request, response, -1), groupOrder);
    		new ExportExcel("拼团订单", GroupOrder.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出拼团订单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("grouporder:groupOrder:import")
	@RequestMapping(value = "exporttoday")
	public AjaxJson exportTodayFile(GroupOrder groupOrder, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			User user = UserUtils.getUser();
			if (user.isShop()) {
				groupOrder.setDataScope(" AND store.user_id = '"+user.getId()+"' ");
			}
			//获取当前时间
			Date date = new Date();
			Date date1 = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24);
			//定义转化为字符串的日期格式
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
			//将时间转化为类似 2020-02-13 16:01:30 格式的字符串
			String b=sdf.format(date1);
			String e=sdf.format(date);
			Date begin=sdf.parse(b);
			Date end=sdf.parse(e);
			groupOrder.setBeginCreateDate(begin);
			groupOrder.setEndCreateDate(end);
			groupOrder.setDataScope(" and  a.state in ('1','2','3','4') ");
			String fileName = "拼团订单"+b+"到"+e+"数据.xlsx";
			List<GroupOrder> list = groupOrderService.findList(groupOrder);
			new ExportExcel("拼团订单", GroupOrder.class).setDataList(list).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出拼团订单记录失败！失败信息："+e.getMessage());
		}
		return j;
	}

    @ResponseBody
    @RequestMapping(value = "detail")
	public GroupOrder detail(String id) {
		return groupOrderService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("grouporder:groupOrder:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<GroupOrder> list = ei.getDataList(GroupOrder.class);
			for (GroupOrder groupOrder : list){
				try{
					groupOrderService.save(groupOrder);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条拼团订单记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条拼团订单记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入拼团订单失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入拼团订单数据模板
	 */
	@ResponseBody
	@RequiresPermissions("grouporder:groupOrder:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "拼团订单数据导入模板.xlsx";
    		List<GroupOrder> list = Lists.newArrayList();
    		new ExportExcel("拼团订单数据", GroupOrder.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }
}